package com.party.admin.jms.publisher.service.impl;

import com.party.admin.jms.publisher.service.IMallAutoCompletePubulisherService;
import com.party.common.constant.Constant;
import com.party.core.model.system.SysConfig;
import com.party.core.model.system.SysConfigEnum;
import com.party.core.service.system.ISysConfigService;
import org.apache.activemq.ScheduledMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;

/**
 * 商城自动确认收货
 * Created by yifeng
 *
 * @date 2018/6/1 0001
 * @time 下午 15:11
 */
@Service
public class MallAutoCompletePubulisherService implements IMallAutoCompletePubulisherService {
    @Autowired
    private ISysConfigService sysConfigService;

    private JmsTemplate jmsOrderAutoCompletelTemplate;

    public void setJmsOrderAutoCompletelTemplate(JmsTemplate jmsOrderAutoCompletelTemplate) {
        this.jmsOrderAutoCompletelTemplate = jmsOrderAutoCompletelTemplate;
    }

    Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void sendMessage(final String orderId) {
        try {
            // 是否允许开启延迟队列取消订单消息
            SysConfig allowSendConfig = sysConfigService.findByCode(SysConfigEnum.ALLOW_SEND_CANCEL_ORDER.getCode());
            if (null != allowSendConfig && allowSendConfig.getValue().equals("true")) {
                // 单位是分钟
                SysConfig sendTimeConfig = sysConfigService.findByCode(SysConfigEnum.SEND_ORDER_AUTO_COMPLETE_TIME.getCode());
                if (sendTimeConfig != null) {
                    Integer overtime = Integer.valueOf(sendTimeConfig.getValue());
                    jmsOrderAutoCompletelTemplate.send(new MessageCreator() {
                        public Message createMessage(Session session) throws JMSException {
                            System.out.println("消息发送时间：" + System.currentTimeMillis());
                            MapMessage mapMessage = session.createMapMessage();
                            mapMessage.setString(Constant.TYPE_KEY, orderId);
                            long delayTime = overtime * 60 * 1000;
                            mapMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delayTime);
                            return mapMessage;
                        }
                    });
                }
            }
        } catch (Exception e) {
            logger.error("订单取消队列发送消息异常", e);
        }
    }
}
